//
//  ViewController.m
//  NSURLConnectionTest
//
//  Created by wangrui on 13-8-22.
//  Copyright (c) 2013年 PPS. All rights reserved.
//

#import "MyTestConnection.h"

@interface MyTestConnection ()<NSURLConnectionDataDelegate>
{
    BOOL finshed;
    UIImageView *imgv;
}
@end

@implementation MyTestConnection

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    imgv = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    imgv.image = [UIImage imageNamed:@"icon"];
    [self.view addSubview:imgv];
    
    NSURLRequest *requst1 = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
    NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:requst1 delegate:self startImmediately:NO];
    [con scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];//NSRunLoopCommonModes tracking不影响. startImmediately需要设置为NO
    [con start];
  
    [self performSelectorInBackground:@selector(startRequestOnBackground) withObject:nil];
}

- (void)startRequestOnBackground{
    NSURLRequest *requst = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
    [[NSURLConnection alloc]initWithRequest:requst delegate:self startImmediately:YES];

    while (!finshed) {
        //这里得用NSDefaultRunLoopMode
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }
}


/*
 *主线程中请求的NSURLConnection的代理方法将在主线程执行
 *其他线程请求的将在该线程执行回调方法
 */

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if ([NSThread isMainThread]) {
        NSLog(@"main:%@",[[connection currentRequest].URL description]);
        NSLog(@"main:finised");
    }
    else{
        //尝试在其他线程更新UI，看看有什么反应
        imgv.center = self.view.center;//咦，能正常更新
        NSLog(@"other theads: %@",[[connection currentRequest].URL description]);
        NSLog(@"other theads: finished");
        finshed = YES;
    }
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
